//
//  PictureSelectorViewController.swift
//  SinaWeibo
//
//  Created by 张洪毓 on 15/11/20.
//  Copyright © 2015年 张洪毓. All rights reserved.
//

import UIKit
import SnapKit
private let reuseIdentifier = "Cell"
private let column: CGFloat = 4
private let pictureCellMargin: CGFloat = 10
private let maxImageCount = 3
class PictureSelectorViewController: UICollectionViewController {
    
    lazy var imageList = [UIImage]()
    
    init() {
        let layout = UICollectionViewFlowLayout()
        //设置layout
        let w = (kScreenSize.width - (column + 1) * pictureCellMargin) / column
        layout.itemSize = CGSize(width: w, height: w)
        layout.minimumInteritemSpacing = pictureCellMargin
        layout.minimumLineSpacing = pictureCellMargin
        layout.sectionInset = UIEdgeInsets(top: pictureCellMargin, left: pictureCellMargin, bottom: 0, right: pictureCellMargin)
        //指定的构造函数
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.registerClass(PictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delta = (imageList.count == maxImageCount ? 0 : 1)
        return imageList.count + delta
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectorCell
        cell.backgroundColor = UIColor.randomColor()
        cell.selectorCellDelegate = self
        if indexPath.item == imageList.count {
            cell.image = nil
        }else {
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
}

extension PictureSelectorViewController: PictureSelectorCellDelegate {
 
    func userWillAddicture(cell: PictureSelectorCell) {
        if cell.image != nil {
            print("已经添加图片")
            return
        }
        print("用户添加图片")
        let picker = UIImagePickerController()
        picker.delegate = self
//        picker.allowsEditing = true
        presentViewController(picker, animated: true, completion: nil)
    }
    
    func userWillDeletePicture(cell: PictureSelectorCell) {
        print("用户删除图片")
        let indextPath = collectionView?.indexPathForCell(cell)
        self.imageList.removeAtIndex(indextPath!.item)
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            cell.alpha = 0
            }) { (_) -> Void in
                cell.alpha = 1
                self.collectionView?.reloadData()
        }
    }
    
}

extension PictureSelectorViewController: UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        imageList.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

@objc protocol PictureSelectorCellDelegate: NSObjectProtocol {
    optional func userWillAddicture(cell: PictureSelectorCell)
    optional func userWillDeletePicture(cell: PictureSelectorCell)
}

class PictureSelectorCell: UICollectionViewCell {
    
    //定义代理
    weak var selectorCellDelegate: PictureSelectorCellDelegate?
    
    @objc private func addBtnDidClick() {
        selectorCellDelegate?.userWillAddicture?(self)
    }
    
    @objc private func deleteBtnDidClick() {
        selectorCellDelegate?.userWillDeletePicture?(self)
    }
    
    var image: UIImage? {
        didSet {
            deleteBtn.hidden = (image == nil)
            if image != nil {
                addBtn.setBackgroundImage(image, forState: .Normal)
            } else {
                addBtn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //设置UI
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: "deleteBtnDidClick", forControlEvents: .TouchUpInside)
        
    }
    
    //懒加载控件
    private lazy var addBtn = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    private lazy var deleteBtn = UIButton(title: nil, backImage: "compose_photo_close", color: nil)

    
}






















